package com.leetcode.listnode.demo1;

/**
 * @Author : Zan
 * @Create : 2024/5/12 16:18
 * @ClassName : Test
 * @Description : https://leetcode.cn/problems/remove-linked-list-elements/description/   移除链表元素
 */

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Test {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 6, 3, 4, 5, 6};
//        int[] arr = new int[]{7,7,7,7};
        ListNode listNode = initLinkedList(arr);
        Solution solution = new Solution();
        ListNode listNode1 = solution.removeElements(listNode, 6);
        System.out.println(listNode1);
    }

    public static ListNode initLinkedList(int[] array) {
        ListNode head = null, current = null;
        for (int i = 0; i < array.length; i++) {
            ListNode newNode = new ListNode(array[i]);
            if (i == 0) { // 头节点
                // 由于head = current，因此当current在变化的时候，head也在变化
                head = newNode;
//                newNode = new Node(array[i]); // 如果在此将newNode重新定义，指向的是不同的堆数据，因此head就只是一个Node普通对象，单节点的链表
                current = newNode;
            } else { // 后面的节点
                current.next = newNode;
                current = newNode;
            }
        }
        return head;
    }
}

// 不用虚拟头节点
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode current = head;
        while (current != null && current.next != null) {
            if (current.next.val == val) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
        return head;
    }
}

// 使用了虚拟头节点
class Solution2 {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(-1, head);
        ListNode current = dummy;
        while (current.next != null) {
            if (current.next.val == val) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
        return dummy.next;
    }
}
